<?php
class Admin_IndexController extends Zend_Controller_Action {
	
	public function preDispatch(){
		$auth = Zend_Auth::getInstance();
		if(!$auth->hasIdentity()){
			if($this->_request->getActionName() != "login"){
				$this->_redirect("/admin/index/login");
			}
		}
	}
	
	public function init() {
		/* Initialize action controller here */
		$auth = Zend_Auth::getInstance();
		$infoUser = $auth->getIdentity();
		$this->view->fullName = $infoUser->ADMINNAME;
	}
	public function indexAction() {
		Zend_Layout::startMvc(array("layoutPath"=>APPLICATION_PATH."/layouts/scripts","layout"=>"admin"));
	}
	
	public function loginAction(){
		$this->_helper->layout()->disableLayout();
		$this->view->headTitle("Đăng Nhập","PREPEND");
		$auth = Zend_Auth::getInstance();
		if($this->getRequest()->isPost()){
			$db = Zend_Registry::get("connectDb");
			$authAdapter = new Zend_Auth_Adapter_DbTable($db);
			$authAdapter->setTableName("admin")->setIdentityColumn("ADMINNAME")->setCredentialColumn("PASSWORD");
			
			$uName = $this->_request->getParam("UName");
			$Pass = $this->_request->getParam("Pass");
			
			$authAdapter->setIdentity($uName);
			$authAdapter->setCredential(md5("H0meVjet".md5($Pass)));
			
			$select = $authAdapter->getDbSelect();
			$select->where("STATUS = 1");
			
			$result = $auth->authenticate($authAdapter);
			$flag = false;
			if($result->isValid()){
				$data = $authAdapter->getResultRowObject(null,array("PASSWORD"));
				$auth->getStorage()->write($data);
				$flag = true;
			}else{
				$this->view->error = "Đăng nhập không thành công vui lòng kiểm tra lại username và mật khẩu!";
			}
			if($flag == true){
				$this->_redirect("/admin/index");
			}
		}
		if($auth->hasIdentity()){
			$this->_redirect("admin/index");
		}
	}
	
	public function logoutAction() {
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->_redirect("/admin/index/login");
	}
	
}

